using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;
using PdfLib;

namespace Workflows.Components.TextMining.PdfBookmarkExtraction
{
    /// <summary>
    /// 
    /// </summary>
    public partial class PdfBookmarkExtractionEditor : Form, IComponentEditor 
    {
        private object _OwnerActivityNode;
        private PdfBookmarkExtractionComponent _bookmarkExtractionComponent;

        /// <summary>
        /// 
        /// </summary>
        public PdfBookmarkExtractionEditor()
        {
            InitializeComponent();
        }

        private void PdfBookmarkExtractionEditor_Load(object sender, EventArgs e)
        {

        }

        public event UpdateComponentSettings UpdateComponentSettingEvent;
        /// <summary></summary>
        public object OwnerActivityNode
        {
            get { return _OwnerActivityNode; }
            set { _OwnerActivityNode = value; }
        }

        /// <summary></summary>
        public Type WorkflowComponentType
        {
            get { return typeof(PdfBookmarkExtractionComponent); }
        }

        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents,
                                 object activityNode, WorkflowComponentBase wfComponent)
        {
            this._OwnerActivityNode = activityNode;
            this._bookmarkExtractionComponent = (PdfBookmarkExtractionComponent) wfComponent;

            // src
            this.txt_SrcConnStr.Text = this._bookmarkExtractionComponent.SrcConnStr;
            this.rt_SelectSql.Text = this._bookmarkExtractionComponent.SelectSql;
            this.cbo_FilePathField.Items.Clear();
            this.cbo_SrcIDField.Items.Clear();
            if(!string.IsNullOrEmpty(this.txt_SrcConnStr.Text) && !string.IsNullOrEmpty(this.rt_SelectSql.Text))
            {
                TableColumn[] srcCols = DbUtil.GetTableColumns(
                    DataProviderType.MSSQL, this.txt_SrcConnStr.Text, this.rt_SelectSql.Text);
                if(srcCols !=null && srcCols.Length>0)
                {
                    foreach(TableColumn col in srcCols)
                    {
                        this.cbo_FilePathField.Items.Add(col.ColumnName);
                        this.cbo_SrcIDField.Items.Add(col.ColumnName);
                    }

                    this.SelectFieldInComboBox(this.cbo_FilePathField,this._bookmarkExtractionComponent.FilePathField);
                    this.SelectFieldInComboBox(this.cbo_SrcIDField,this._bookmarkExtractionComponent.SrcIDField);
                }
            }

            // bookmark 
            if(!string.IsNullOrEmpty(this._bookmarkExtractionComponent.BookmarkTitle))
            {
                this.rd_BookmarkByTitle.Checked = true;
                this.txt_BookmarkTitle.Text = this._bookmarkExtractionComponent.BookmarkTitle;
            }
            else if(!string.IsNullOrEmpty(this._bookmarkExtractionComponent.BookmarkPath))
            {
                this.rd_BookmarkByPath.Checked = true;
                this.txt_BookmarkPath.Text = this._bookmarkExtractionComponent.BookmarkPath;
            }
            else if(this._bookmarkExtractionComponent.BookmarkSearchPatterns!=null && this._bookmarkExtractionComponent.BookmarkSearchPatterns.Length>0)
            {
                this.rd_BookmarkByPattern.Checked = true;
                this.txt_BookmarkPatterns.Text = StringUtil.ToString(this._bookmarkExtractionComponent.BookmarkSearchPatterns, Environment.NewLine);
            }
            this.ck_AcrossMultipleBookmarks.Checked = false;
            if(this._bookmarkExtractionComponent.AcrossMultipleBookmarks)
            {
                this.ck_AcrossMultipleBookmarks.Checked = true;
                this.txt_ToBookmarkTitle.Text = this._bookmarkExtractionComponent.ToBookmarkTitle;
                this.txt_ToBookmarkPath.Text = this._bookmarkExtractionComponent.ToBookmarkPath;
                this.txt_BookmarkPatterns.Text =
                    StringUtil.ToString(this._bookmarkExtractionComponent.ToBookmarkPatterns, Environment.NewLine);
            }

            // filter 
            this.dv_Filters.Rows.Clear();
            if(this._bookmarkExtractionComponent.ContentFilters !=null && this._bookmarkExtractionComponent.ContentFilters.Count>0)
            {
                foreach(PdfContentFilter filter in this._bookmarkExtractionComponent.ContentFilters)
                {
                    DataGridViewRow dr = new DataGridViewRow();
                    DataGridViewTextBoxCell cellHeader=new DataGridViewTextBoxCell();
                    cellHeader.Value = filter.HeaderPattern;
                    dr.Cells.Add(cellHeader);
                    DataGridViewCheckBoxCell cellSkipHeader=new DataGridViewCheckBoxCell();
                    cellSkipHeader.Value = filter.SkipHeader;
                    dr.Cells.Add(cellSkipHeader);
                    DataGridViewTextBoxCell cellFooter=new DataGridViewTextBoxCell();
                    cellFooter.Value = filter.FooterPattern;
                    dr.Cells.Add(cellFooter);
                    DataGridViewCheckBoxCell cellSkipFooter = new DataGridViewCheckBoxCell();
                    cellSkipFooter.Value = filter.SkipFooter;
                    dr.Cells.Add(cellSkipFooter);
                    this.dv_Filters.Rows.Add(dr);
                }
            }
            this.ck_BoxedContent.Checked = this._bookmarkExtractionComponent.UseBoxedContent;
            this.num_MinW.Value = (decimal)this._bookmarkExtractionComponent.MinWidth;
            this.num_MinH.Value = (decimal)this._bookmarkExtractionComponent.MinHeight;

            this.txt_ConnStr.Text = this._bookmarkExtractionComponent.TgtConnStr;
            this.cbo_TgtTables.Items.Clear();
            if(!string.IsNullOrEmpty(this.txt_ConnStr.Text))
            {
                string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL, string.Empty, this.txt_ConnStr.Text);
                if(tblNames !=null && tblNames.Length>0)
                {
                    foreach(string tblName in tblNames)
                    {
                        this.cbo_TgtTables.Items.Add(tblName);
                    }
                }
            }

            this.SelectFieldInComboBox(this.cbo_TgtTables,this._bookmarkExtractionComponent.TargetTableName);
            this.SelectFieldInComboBox(this.cbo_TgtIDField,this._bookmarkExtractionComponent.TgtIDField);
            this.SelectFieldInComboBox(this.cbo_BookmarkContentField,this._bookmarkExtractionComponent.BookmarkContentFieldName);
            this.SelectFieldInComboBox(this.cbo_FromPageField, this._bookmarkExtractionComponent.ExtractFromPageField);
            this.SelectFieldInComboBox(this.cbo_FromPosField, this._bookmarkExtractionComponent.ExtractFromPosField);
            this.SelectFieldInComboBox(this.cbo_ToPageField, this._bookmarkExtractionComponent.ExtractToPageField);
            this.SelectFieldInComboBox(this.cbo_ToPosField, this._bookmarkExtractionComponent.ExtractToPosField);
            this.SelectFieldInComboBox(this.cbo_FlagField, this._bookmarkExtractionComponent.FlagField);
            this.SelectFieldInComboBox(this.cbo_UpdField, this._bookmarkExtractionComponent.UpdField);
        }

        private void SelectFieldInComboBox(ComboBox comboBox, string item)
        {
            if(comboBox.Items.Count>0 && !string.IsNullOrEmpty(item))
            {
                for(int i=0;i<comboBox.Items.Count;i++)
                {
                    if(comboBox.Items[i].ToString()==item)
                    {
                        comboBox.SelectedIndex = i;
                        break;
                    }
                }
            }
        }

        /// <summary></summary>
        public void SaveSettings()
        {
            // src 
            this._bookmarkExtractionComponent.SrcConnStr = this.txt_SrcConnStr.Text;
            this._bookmarkExtractionComponent.SelectSql = this.rt_SelectSql.Text;
            this._bookmarkExtractionComponent.FilePathField = this.cbo_FilePathField.Text;
            this._bookmarkExtractionComponent.SrcIDField = this.cbo_SrcIDField.Text;
            // bookmark 
            this._bookmarkExtractionComponent.BookmarkTitle = string.Empty;
            this._bookmarkExtractionComponent.ToBookmarkTitle = string.Empty;
            if(this.rd_BookmarkByTitle.Checked)
            {
                this._bookmarkExtractionComponent.BookmarkTitle = this.txt_BookmarkTitle.Text;
                this._bookmarkExtractionComponent.ToBookmarkTitle = this.txt_ToBookmarkTitle.Text;
            }
            this._bookmarkExtractionComponent.BookmarkPath = string.Empty;
            this._bookmarkExtractionComponent.ToBookmarkPath = string.Empty;
            if(this.rd_BookmarkByPath.Checked)
            {
                this._bookmarkExtractionComponent.BookmarkPath = this.txt_BookmarkPath.Text;
                this._bookmarkExtractionComponent.ToBookmarkPath = this.txt_ToBookmarkPath.Text;
            }
            this._bookmarkExtractionComponent.BookmarkSearchPatterns = null;
            this._bookmarkExtractionComponent.ToBookmarkPatterns = null;
            if (this.rd_BookmarkByPattern.Checked)
            {
                this._bookmarkExtractionComponent.BookmarkSearchPatterns = StringUtil.Split(this.txt_BookmarkPatterns.Text, Environment.NewLine);
                this._bookmarkExtractionComponent.ToBookmarkPatterns =
                    StringUtil.Split(this.txt_ToBookmarkPatterns.Text, Environment.NewLine);
            }
            this._bookmarkExtractionComponent.AcrossMultipleBookmarks = this.ck_AcrossMultipleBookmarks.Checked;
            // filter 
            this._bookmarkExtractionComponent.ContentFilters=new List<PdfContentFilter>();
            foreach(DataGridViewRow dr in this.dv_Filters.Rows)
            {
                if(!dr.IsNewRow && (dr.Cells[0].Value !=null || dr.Cells[2].Value !=null))
                {
                    PdfContentFilter filter = new PdfContentFilter(string.Empty, false, string.Empty, false);
                    if(dr.Cells[0].Value !=null)
                        filter.HeaderPattern = (string) dr.Cells[0].Value;
                    if(dr.Cells[1].Value !=null)
                        filter.SkipHeader = (bool) dr.Cells[1].Value;
                    if(dr.Cells[2].Value !=null)
                        filter.FooterPattern = (string) dr.Cells[2].Value;
                    if(dr.Cells[3].Value !=null)
                        filter.SkipFooter = (bool) dr.Cells[3].Value;
                    this._bookmarkExtractionComponent.ContentFilters.Add(filter);
                }
            }
            this._bookmarkExtractionComponent.UseBoxedContent = this.ck_BoxedContent.Checked;
            this._bookmarkExtractionComponent.MinWidth = (float)this.num_MinW.Value;
            this._bookmarkExtractionComponent.MinHeight = (float)this.num_MinH.Value;
            // tgt 
            this._bookmarkExtractionComponent.TgtConnStr = this.txt_ConnStr.Text;
            this._bookmarkExtractionComponent.TargetTableName = this.cbo_TgtTables.Text;
            this._bookmarkExtractionComponent.TgtIDField = this.cbo_TgtIDField.Text;
            this._bookmarkExtractionComponent.BookmarkContentFieldName = this.cbo_BookmarkContentField.Text;
            this._bookmarkExtractionComponent.ExtractFromPageField = this.cbo_FromPageField.Text;
            this._bookmarkExtractionComponent.ExtractFromPosField = this.cbo_FromPosField.Text;
            this._bookmarkExtractionComponent.ExtractToPageField = this.cbo_ToPageField.Text;
            this._bookmarkExtractionComponent.ExtractToPosField = this.cbo_ToPosField.Text;
            this._bookmarkExtractionComponent.FlagField = this.cbo_FlagField.Text;
            this._bookmarkExtractionComponent.UpdField = this.cbo_UpdField.Text;
        }

        /// <summary></summary>
        public TestResult Test()
        {
            throw new NotImplementedException();
        }

        private void DisplayBookmarks(List<PdfBookmark> bookmarks)
        {
            this.tree_Bookmarks.Nodes.Clear();
            Dictionary<string,TreeNode> parentNodes=new Dictionary<string, TreeNode>();
            if(bookmarks !=null && bookmarks.Count>0)
            {
                bookmarks.Sort();
                foreach(PdfBookmark bookmark in bookmarks)
                {
                    TreeNode bookmarkTn = new TreeNode(bookmark.Title);
                    bookmarkTn.ImageIndex = 0;
                    bookmarkTn.SelectedImageIndex = 0;
                    bookmarkTn.Tag = bookmark;
                    if(string.IsNullOrEmpty(bookmark.Path))
                    {
                        this.tree_Bookmarks.Nodes.Add(bookmarkTn);
                    }
                    else
                    {
                        if(bookmark.Path.IndexOf(".")>0)
                        {
                            string parentPath = bookmark.Path.Substring(0, bookmark.Path.LastIndexOf("."));
                            if (parentNodes.ContainsKey(parentPath))
                            {
                                TreeNode parentNode = parentNodes[parentPath];
                                parentNode.Nodes.Add(bookmarkTn);
                            }
                            else
                            {
                                this.tree_Bookmarks.Nodes.Add(bookmarkTn);
                            }
                        }
                        else
                        {
                            this.tree_Bookmarks.Nodes.Add(bookmarkTn);
                        }
                    }

                    parentNodes.Add(bookmark.Path, bookmarkTn);
                }
                this.tree_Bookmarks.ExpandAll();
            }
            this.tree_Bookmarks.Refresh();
        }

        private void tree_Bookmarks_MouseUp(object sender, MouseEventArgs e)
        {
            this.tree_Bookmarks.SelectedNode = this.tree_Bookmarks.GetNodeAt(e.X, e.Y);

            if(this.tree_Bookmarks.SelectedNode !=null)
            {
                PdfBookmark bookmark = (PdfBookmark) this.tree_Bookmarks.SelectedNode.Tag;
                this.txt_BookmarkTitle.Text = bookmark.Title;
                this.txt_BookmarkPath.Text = bookmark.Path;

                if(!string.IsNullOrEmpty(this.txt_TestFilePath.Text) && File.Exists(this.txt_TestFilePath.Text))
                {
                    try
                    {
                        string bookmarkContent =
                            PdfBookmarkReader.ReadBookmarkContent(
                                this.txt_TestFilePath.Text, 
                                bookmark);

                        // this.axAcroPDF1.LoadFile(this.txt_PdfFilePath.Text);
                        this.axAcroPDF1.gotoFirstPage();
                        int pageNum = 1;
                        while (pageNum < bookmark.FromPageNumber)
                        {
                            this.axAcroPDF1.gotoNextPage();
                            pageNum++;
                        }
                        this.rt_BookmarkContent.Text =
                            this.FilterBookmarkContent(this.txt_TestFilePath.Text, bookmark.FromPageNumber,
                                                       bookmarkContent);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private string FilterBookmarkContent(
            string pdfFilePath, int pageNum, string bookmarkContent)
        {
            this.SaveSettings();
            if(this.ck_BoxedContent.Checked)
            {
                float minW = (float) this.num_MinW.Value;
                float minH = (float) this.num_MinH.Value;
                bookmarkContent = PdfTextReader.ReadBoxedContent(pdfFilePath, pageNum, minW, minH);
            }

            string filteredContent = bookmarkContent;
            if(!string.IsNullOrEmpty(this.txt_HeaderFilter.Text))
            {
                string headerFilter = StringUtil.BuildRegexMatchPattern(this.txt_HeaderFilter.Text);
                if (Regex.IsMatch(filteredContent, headerFilter, RegexOptions.IgnoreCase))
                {
                    Match match = Regex.Match(filteredContent, headerFilter, RegexOptions.IgnoreCase);
                    if(this.ck_RemoveHeaderLine.Checked)
                    {
                        List<PdfTextLine> pdfLines = PdfTextReader.ReadPageContentAsLines(pdfFilePath, pageNum, 8.0);
                        pdfLines.Sort();
                        int startPos = -1;
                        foreach(PdfTextLine line in pdfLines)
                        {
                            Match match2 = Regex.Match(line.LineContent, headerFilter, RegexOptions.IgnoreCase);
                            if(match2.Success)
                            {
                                if (filteredContent.IndexOf(line.LineContent) >= 0)
                                {
                                    startPos = filteredContent.IndexOf(line.LineContent) + line.LineContent.Length;
                                }
                            }
                        }
                        if (startPos > 0)
                            filteredContent = filteredContent.Substring(startPos);
                        else
                            filteredContent = filteredContent.Substring(match.Index + match.Value.Length);
                    }
                    else
                    {
                        List<PdfTextLine> pdfLines = PdfTextReader.ReadPageContentAsLines(pdfFilePath, pageNum, 8.0);
                        pdfLines.Sort();
                        int startPos = -1;
                        foreach (PdfTextLine line in pdfLines)
                        {
                            Match match2 = Regex.Match(line.LineContent, headerFilter, RegexOptions.IgnoreCase);
                            if (match2.Success)
                            {
                                startPos = filteredContent.IndexOf(line.LineContent);
                            }
                        }
                        if (startPos > 0)
                            filteredContent = filteredContent.Substring(startPos);
                        else
                            filteredContent = filteredContent.Substring(match.Index);
                    }
                    
                }
            }
            if(!string.IsNullOrEmpty(this.txt_FooterFilter.Text))
            {
                string footerFilter = StringUtil.BuildRegexMatchPattern(this.txt_FooterFilter.Text);
                if (Regex.IsMatch(filteredContent, footerFilter, RegexOptions.IgnoreCase))
                {
                    Match match = Regex.Match(filteredContent, footerFilter, RegexOptions.IgnoreCase);
                    if(this.ck_RemoveFooterLine.Checked)
                    {
                        List<PdfTextLine> pdfLines = PdfTextReader.ReadPageContentAsLines(pdfFilePath, pageNum, 8.0);
                        pdfLines.Sort();
                        int startPos = -1;
                        foreach (PdfTextLine line in pdfLines)
                        {
                            Match match2 = Regex.Match(line.LineContent, footerFilter, RegexOptions.IgnoreCase);
                            if (match2.Success)
                            {
                                startPos = filteredContent.IndexOf(line.LineContent);
                            }
                        }
                        if (startPos > 0)
                            filteredContent = filteredContent.Substring(0, startPos);
                        else
                            filteredContent = filteredContent.Substring(0, match.Index);
                    }
                    else
                    {
                        List<PdfTextLine> pdfLines = PdfTextReader.ReadPageContentAsLines(pdfFilePath, pageNum, 8.0);
                        pdfLines.Sort();
                        int startPos = -1;
                        foreach (PdfTextLine line in pdfLines)
                        {
                            Match match2 = Regex.Match(line.LineContent, footerFilter, RegexOptions.IgnoreCase);
                            if (match2.Success)
                            {
                                if (filteredContent.IndexOf(line.LineContent) >= 0)
                                {
                                    startPos = filteredContent.IndexOf(line.LineContent) + line.LineContent.Length;
                                }
                            }
                        }
                        if (startPos > 0)
                            filteredContent = filteredContent.Substring(0, startPos);
                        else
                            filteredContent = filteredContent.Substring(0, match.Index + match.Value.Length);
                    }
                }
            }

            return filteredContent;
        }

        #region bookmark 
        private void rd_BookmarkByTitle_CheckedChanged(object sender, EventArgs e)
        {
            this.SwitchBookmarkSearcher();
        }

        private void rd_BookmarkByPath_CheckedChanged(object sender, EventArgs e)
        {
            this.SwitchBookmarkSearcher();
        }

        private void rd_BookmarkByPattern_CheckedChanged(object sender, EventArgs e)
        {
            this.SwitchBookmarkSearcher();
        }

        private void SwitchBookmarkSearcher()
        {
            if (this.rd_BookmarkByTitle.Checked)
            {
                this.txt_BookmarkTitle.Enabled = true;
                this.txt_ToBookmarkTitle.Enabled = true;
                this.txt_BookmarkPath.Enabled = false;
                this.txt_ToBookmarkPath.Enabled = false;
                this.txt_BookmarkPatterns.Enabled = false;
                this.txt_ToBookmarkPatterns.Enabled = false;
            }
            else if (this.rd_BookmarkByPath.Checked)
            {
                this.txt_BookmarkTitle.Enabled = false;
                this.txt_ToBookmarkTitle.Enabled = false;
                this.txt_BookmarkPath.Enabled = true;
                this.txt_ToBookmarkPath.Enabled = true;
                this.txt_BookmarkPatterns.Enabled = false;
                this.txt_ToBookmarkPatterns.Enabled = false;
            }
            else if (this.rd_BookmarkByPattern.Checked)
            {
                this.txt_BookmarkTitle.Enabled = false;
                this.txt_ToBookmarkTitle.Enabled = false;
                this.txt_BookmarkPath.Enabled = false;
                this.txt_ToBookmarkPath.Enabled = false;
                this.txt_BookmarkPatterns.Enabled = true;
                this.txt_ToBookmarkPatterns.Enabled = true;
            }
        }

        private void ck_AcrossMultipleBookmarks_CheckedChanged(object sender, EventArgs e)
        {
            this.lbl_ToBookmarkTitle.Visible = this.ck_AcrossMultipleBookmarks.Checked;
            this.lbl_ToBookmarkPath.Visible = this.ck_AcrossMultipleBookmarks.Checked;
            this.lbl_ToBookmarkPatterns.Visible = this.ck_AcrossMultipleBookmarks.Checked;
            this.txt_ToBookmarkTitle.Visible = this.ck_AcrossMultipleBookmarks.Checked;
            this.txt_ToBookmarkPath.Visible = this.ck_AcrossMultipleBookmarks.Checked;
            this.txt_ToBookmarkPatterns.Visible = this.ck_AcrossMultipleBookmarks.Checked;
        }
        #endregion

        #region filter 
        private void btn_AddFilter_Click(object sender, EventArgs e)
        {
            DataGridViewRow dr = new DataGridViewRow();
            DataGridViewTextBoxCell cellHeader = new DataGridViewTextBoxCell();
            cellHeader.Value = this.txt_HeaderFilter.Text;
            dr.Cells.Add(cellHeader);
            DataGridViewCheckBoxCell cellSkipHeader = new DataGridViewCheckBoxCell();
            cellSkipHeader.Value = this.ck_RemoveHeaderLine.Checked;
            dr.Cells.Add(cellSkipHeader);
            DataGridViewTextBoxCell cellFooter = new DataGridViewTextBoxCell();
            cellFooter.Value = this.txt_FooterFilter.Text;
            dr.Cells.Add(cellFooter);
            DataGridViewCheckBoxCell cellSkipFooter = new DataGridViewCheckBoxCell();
            cellSkipFooter.Value = this.ck_RemoveFooterLine.Checked;
            dr.Cells.Add(cellSkipFooter);
            this.dv_Filters.Rows.Add(dr);

        }
        #endregion

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if (this.UpdateComponentSettingEvent != null)
                this.UpdateComponentSettingEvent(this._OwnerActivityNode, this._bookmarkExtractionComponent);
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbo_TgtTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(this.cbo_TgtTables.SelectedIndex>=0 && !string.IsNullOrEmpty(this.txt_ConnStr.Text))
            {
                string connStr = this.txt_ConnStr.Text;
                string tblName = this.cbo_TgtTables.SelectedItem.ToString();
                this.cbo_TgtIDField.Items.Clear();
                this.cbo_BookmarkContentField.Items.Clear();
                this.cbo_FromPageField.Items.Clear();
                this.cbo_FromPosField.Items.Clear();
                this.cbo_ToPageField.Items.Clear();
                this.cbo_ToPosField.Items.Clear();
                this.cbo_FlagField.Items.Clear();
                this.cbo_UpdField.Items.Clear();

                TableColumn[] cols = DbUtil.GetTableColumns(DataProviderType.MSSQL, connStr, string.Empty, tblName);
                if(cols !=null && cols.Length>0)
                {
                    foreach(TableColumn col in cols)
                    {
                        this.cbo_TgtIDField.Items.Add(col.ColumnName);
                        this.cbo_BookmarkContentField.Items.Add(col.ColumnName);
                        this.cbo_FromPageField.Items.Add(col.ColumnName);
                        this.cbo_FromPosField.Items.Add(col.ColumnName);
                        this.cbo_ToPageField.Items.Add(col.ColumnName);
                        this.cbo_ToPosField.Items.Add(col.ColumnName);
                        this.cbo_FlagField.Items.Add(col.ColumnName);
                        this.cbo_UpdField.Items.Add(col.ColumnName);
                    }
                }
            }
        }

        private void btn_Browse2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg=new OpenFileDialog();
            dlg.Filter = "PDF files(*.pdf)|*.pdf|All files(*.*)|*.*";
            if(dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)
            {
                string filePath = dlg.FileName;
                this.txt_TestFilePath.Text = filePath;
                this.axAcroPDF1.LoadFile(filePath);
                List<PdfBookmark> bookmarks = PdfBookmarkReader.GetAllBookmarks(filePath);
                this.DisplayBookmarks(bookmarks);

                PdfBookmark bookmark =
                    this.GetBookmark(filePath,
                                     this.txt_BookmarkTitle.Text, this.txt_BookmarkPath.Text,
                                     StringUtil.Split(this.txt_BookmarkPatterns.Text, Environment.NewLine));
                PdfBookmark toBookmark = null;
                if(this.ck_AcrossMultipleBookmarks.Checked)
                {
                    toBookmark = this.GetBookmark(filePath,
                                                  this.txt_ToBookmarkTitle.Text,
                                                  this.txt_ToBookmarkPath.Text,
                                                  StringUtil.Split(this.txt_ToBookmarkPatterns.Text, Environment.NewLine));
                }

                if(bookmark !=null)
                {
                    this.SaveSettings();
                    string bookmarkContent = string.Empty;
                    if(toBookmark !=null)
                    {
                        bookmarkContent =
                            PdfTextReader.GetContent(filePath, bookmark.FromPageNumber,
                                                     bookmark.FromPosition, toBookmark.FromPageNumber,
                                                     toBookmark.FromPosition);    
                    }
                    else
                    {
                        bookmarkContent = PdfBookmarkReader.ReadBookmarkContent(filePath, bookmark);
                    }

                    string filteredContent =
                        PdfBookmarkExtractionWorker.FilterBookmarkContent(
                            bookmarkContent, filePath, bookmark.FromPageNumber, this.ck_BoxedContent.Checked,
                            (float) this.num_MinW.Value, (float) this.num_MinH.Value);
                    if(this._bookmarkExtractionComponent.ContentFilters !=null && this._bookmarkExtractionComponent.ContentFilters.Count>0)
                    {
                        foreach(PdfContentFilter filter in this._bookmarkExtractionComponent.ContentFilters)
                        {
                            bool matchedFilter = false;
                            if (toBookmark != null)
                            {
                                filteredContent =
                                    PdfBookmarkExtractionWorker.FilterBookmarkContent(
                                        filePath, bookmark.FromPageNumber, toBookmark.FromPageNumber,
                                        filteredContent, filter, ref matchedFilter);
                            }
                            else
                            {
                                filteredContent =
                                    PdfBookmarkExtractionWorker.FilterBookmarkContent(
                                        filePath, bookmark.FromPageNumber, bookmark.ToPageNumber,
                                        filteredContent, filter, ref matchedFilter);
                            }
                            if (matchedFilter)
                                break;
                        }
                    }
                    this.rt_BookmarkContent.Text = filteredContent;
                }
            }
        }

        private void btn_RefreshTables_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_ConnStr.Text))
            {
                this.cbo_TgtTables.Items.Clear();
                string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL,
                                                         string.Empty, this.txt_ConnStr.Text);
                if(tblNames !=null && tblNames.Length>0)
                {
                    foreach(string tblName in tblNames)
                    {
                        this.cbo_TgtTables.Items.Add(tblName);
                    }

                    this.SelectFieldInComboBox(this.cbo_TgtTables,this._bookmarkExtractionComponent.TargetTableName);

                    this.SelectFieldInComboBox(this.cbo_TgtIDField,this._bookmarkExtractionComponent.TgtIDField);
                    this.SelectFieldInComboBox(this.cbo_BookmarkContentField,this._bookmarkExtractionComponent.BookmarkContentFieldName);
                    this.SelectFieldInComboBox(this.cbo_FromPageField,this._bookmarkExtractionComponent.ExtractFromPageField);
                    this.SelectFieldInComboBox(this.cbo_FromPosField, this._bookmarkExtractionComponent.ExtractFromPosField);
                    this.SelectFieldInComboBox(this.cbo_ToPageField,this._bookmarkExtractionComponent.ExtractToPageField);
                    this.SelectFieldInComboBox(this.cbo_ToPosField, this._bookmarkExtractionComponent.ExtractToPosField);
                    this.SelectFieldInComboBox(this.cbo_FlagField,this._bookmarkExtractionComponent.FlagField);
                    this.SelectFieldInComboBox(this.cbo_UpdField, this._bookmarkExtractionComponent.UpdField);
                }
            }
        }

        private void btn_RefreshSrcField_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txt_SrcConnStr.Text) && !string.IsNullOrEmpty(this.rt_SelectSql.Text))
            {
                this.cbo_FilePathField.Items.Clear();
                this.cbo_SrcIDField.Items.Clear();

                TableColumn[] srcCols = DbUtil.GetTableColumns(
                    DataProviderType.MSSQL, this.txt_SrcConnStr.Text, this.rt_SelectSql.Text);
                if (srcCols != null && srcCols.Length > 0)
                {
                    foreach (TableColumn col in srcCols)
                    {
                        this.cbo_FilePathField.Items.Add(col.ColumnName);
                        this.cbo_SrcIDField.Items.Add(col.ColumnName);
                    }

                    this.SelectFieldInComboBox(this.cbo_FilePathField, this._bookmarkExtractionComponent.FilePathField);
                    this.SelectFieldInComboBox(this.cbo_SrcIDField, this._bookmarkExtractionComponent.SrcIDField);
                }
            }
        }


        #region search bookmark
        private PdfBookmark GetBookmark(string filePath,
            string title, string path, string[] searchPatterns)
        {
            if (!string.IsNullOrEmpty(title))
                return PdfBookmarkReader.FindBookmarkByTitle(filePath, title);
            else if (!string.IsNullOrEmpty(path))
                return PdfBookmarkReader.FindBookmarkByPath(filePath, path);
            else if (searchPatterns != null && searchPatterns.Length > 0)
                return PdfBookmarkReader.FindBookmark(filePath, searchPatterns);
            else
                return null;
        }
        #endregion

        

   

    }
}